package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.common.base.BaseApp;
import com.atguigu.edu.realtime.common.constant.Constant;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

public class DimApp extends BaseApp {
    public static void main(String[] args) {
        new DimApp().start(15002 , 4 , "dim_app" , Constant.TOPIC_DB);
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        SingleOutputStreamOperator<JSONObject> dataDs = stream.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String value, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        try {
                            // 转换成JSONObject类型
                            JSONObject jsonObj = JSON.parseObject(value);
                            // 提取database
                            String database = jsonObj.getString("database");
                            // 提取type
                            String type = jsonObj.getString("type");
                            // 提取data
                            JSONObject dataJsonObj = jsonObj.getJSONObject("data");

                            // 判断处理
                            if (
                                    Constant.DB_NAME.equals(database)
                                            &&
                                            (Constant.MAXWELL_TYPE_INSERT.equals(type) || Constant.MAXWELL_TYPE_UPDATE.equals(type) || Constant.MAXWELL_TYPE_DELETE.equals(type) || Constant.MAXWELL_TYPE_BOOTSTRAP_INSERT.equals(type))
                                            &&
                                            dataJsonObj != null && dataJsonObj.size() >= 2
                            ) {
                                out.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            System.out.println("DimApp  过滤掉脏数据" + value);
                        }
                    }
                }
        );
        dataDs.print("ELT");
    }
}
